<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Bankuai;
use fast\Http;
use think\Db;
use Exception;
use think\exception\PDOException;

/**
 * 设备管理
 *
 * @icon fa fa-circle-o
 */
class Equipment extends Backend
{

    /**
     * Equipment模型对象
     * @var \app\admin\model\Equipment
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Equipment;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
			
			/* $accessToken = getAccessToken();
			$result = Http::post('https://open.ys7.com/api/lapp/device/list', array('accessToken'=>$accessToken));
			$result = json_decode($result, true);
			foreach($result['data'] as $vo)
			{
				$shebei = \app\admin\model\Equipment::get(['device_serial'=>$vo['deviceSerial']]);
				if($shebei)
				{
					$shebei->device_name = $vo['deviceName'];
					$shebei->device_type = $vo['deviceType'];
					$shebei->device_version = $vo['deviceVersion'];
					$shebei->status = $vo['status'];
					$shebei->defence = $vo['defence'];
					$shebei->createtime = substr($vo['addTime'], 0, 10);
					$shebei->updatetime = substr($vo['updateTime'], 0, 10);
					$shebei->parentCategory = $vo['parentCategory'];
					$shebei->riskLevel = $vo['riskLevel'];
					$shebei->netAddress = $vo['netAddress'];
					
					$shebei->save();
				}
				else
				{
					$date = array(
						'device_serial' => $vo['deviceSerial'],
						'device_name'  => $vo['deviceName'],
						'device_type'  => $vo['deviceType'],
						'device_version'  => $vo['deviceVersion'],
						'status'  => $vo['status'],
						'defence'  => $vo['defence'],
						'createtime'  => substr($vo['addTime'], 0, 10),
						'updatetime'  => substr($vo['updateTime'], 0, 10),
						'parentCategory'  => $vo['parentCategory'],
						'riskLevel'  => $vo['riskLevel'],
						'netAddress'  => $vo['netAddress'],
					);
					db('equipment')->insert($date);
				}
			} */
		
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
			
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('bankuai.bk_name');

            $list = $this->model
                    ->with(['bankuai'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

	/**
     * 添加
     */
    public function add()
    {
		if ($this->request->isPost()) {
            $this->token();
			
			$params = $this->request->post("row/a");
			if (empty($params)) {
				$this->error(__('Parameter %s can not be empty', ''));
			}
		
			/* $accessToken = getAccessToken();
			$result = Http::post('https://open.ys7.com/api/lapp/device/add', array('accessToken'=>$accessToken, 'deviceSerial'=>$params['device_serial'], 'validateCode'=>$params['validate_code']));
			$result = json_decode($result, true);
			if($result['code'] == 200)
			{ */
				$shebei = \app\admin\model\Equipment::create($params);
				if ($shebei === false) {
					$this->error(__('No rows were inserted'));
				}
				$bk = \app\admin\model\Bankuai::get($params['bk_id']);
				$bk->shebei = $bk->shebei.','.$shebei->id;
				$bk->save();
				
				$this->success();
			/* }
			else
			{
				$this->error($result['msg']);
			} */
		}
		
		$this->view->assign('bkList', build_select('row[bk_id]', \app\admin\model\Bankuai::column('id,bk_name'), [], ['class' => 'form-control selectpicker']));
		
        return parent::add();
    }
	
	public function edit($ids = null)
	{
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
		
		if ($this->request->isPost()) {
            $this->token();
			
			$params = $this->request->post("row/a");
			if (empty($params)) {
				$this->error(__('Parameter %s can not be empty', ''));
			}

			if($row->device_name != trim($params['device_name']))
			{		
				$accessToken = getAccessToken();
				$result = Http::post('https://open.ys7.com/api/lapp/device/name/update', array('accessToken'=>$accessToken, 'deviceSerial'=>$params['device_serial'], 'deviceName'=>$params['device_name']));
				$result = json_decode($result, true);
				if($result['code'] != 200)
				{
					$this->error($result['msg']);
				}
			}
			
			if($row->bk_id != intval($params['bk_id']))
			{
				if($row->bk_id)
				{
					$old_bk = \app\admin\model\Bankuai::get($row->bk_id);
					$old_shebei = explode(',', $old_bk->shebei);
					$old_bk->shebei = implode(',', array_diff($old_shebei, [$row['id']]));
					$old_bk->save();
				}
				
				$bk = \app\admin\model\Bankuai::get($params['bk_id']);
				$shebei = explode(',', $bk->shebei);
				if(!in_array($row['id'], $shebei))
				{
					$bk->shebei = $bk->shebei.','.$row['id'];
					$bk->save();
				}
			}
			
			$result = $row->allowField(true)->save($params);
			if (false === $result) {
				$this->error(__('No rows were updated'));
			}
				
			$this->success();
		}
		
		$this->view->assign('bkList', build_select('row[bk_id]', \app\admin\model\Bankuai::column('id,bk_name'), $row['bk_id'], ['class' => 'form-control selectpicker']));
		
		$this->view->assign('row', $row);
        return $this->view->fetch();
	}
	
	public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
			//$accessToken = getAccessToken();
            foreach ($list as $item) {
				/* $result = Http::post('https://open.ys7.com/api/lapp/device/delete', array('accessToken'=>$accessToken, 'deviceSerial'=>$item['device_serial']));
				$result = json_decode($result, true);
				if($result['code'] != 200)
				{
					throw new Exception($result['msg']);
				} */
				
				$bankuai = \app\admin\model\Bankuai::get($item['bk_id']);
				$shebei = explode(',', $bankuai->shebei);
				$bankuai->shebei = implode(',', array_diff($shebei, [$item['id']]));
				$bankuai->save();
				
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
	
	public function bankuai()
	{
		$list = [];
		
		$bk_list = Bankuai::field('id, bk_name')->select();
		foreach($bk_list as $vo)
		{
			$list[$vo['id']] = $vo['bk_name'];
		}
		return json($list);
	}
}
